import { useState, useEffect } from 'react';
import apiClient from '../api/axios';
import { Link } from 'react-router-dom';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import remarkMath from 'remark-math';
import rehypeKatex from 'rehype-katex';
import DOMPurify from 'dompurify';
import 'katex/dist/katex.min.css'; // 引入KaTeX的CSS样式

function DashboardPage() {
    const [knowledgePoints, setKnowledgePoints] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState('');

    useEffect(() => {
        const fetchKnowledgePoints = async () => {
            try {
                setLoading(true);
                const response = await apiClient.get('/knowledge-points');
                setKnowledgePoints(response.data);
            } catch (err) {
                setError('获取知识点失败');
                console.error(err);
            } finally {
                setLoading(false);
            }
        };

        fetchKnowledgePoints();
    }, []); // 第二个参数是依赖数组，空数组[]表示这个effect只在组件首次挂载时运行一次

    // 动态导入 mermaid 并初始化
    useEffect(() => {
        if (!loading && !error && knowledgePoints.length > 0) {
            const initMermaid = async () => {
                try {
                    const mermaidModule = await import('mermaid');
                    const mermaid = mermaidModule.default;
                    
                    // 初始化 mermaid
                    mermaid.initialize({ 
                        startOnLoad: false, // 我们会手动控制渲染
                        theme: 'default',
                        securityLevel: 'loose' // 注意：在生产环境中需要更严格的安全设置
                    });
                    
                    // 延迟一点时间确保 DOM 已经更新
                    setTimeout(() => {
                        try {
                            mermaid.run();
                        } catch (err) {
                            console.error('Mermaid rendering error:', err);
                        }
                    }, 100);
                } catch (err) {
                    console.error('Failed to load mermaid:', err);
                }
            };
            
            initMermaid();
        }
    }, [knowledgePoints, loading, error]);

    const handleDelete = async (id) => {
        if (window.confirm('你确定要删除这个知识点吗？')) {
            try {
                await apiClient.delete(`/knowledge-points/${id}`);
                // 从前端状态中移除被删除的项，避免刷新页面
                setKnowledgePoints(knowledgePoints.filter(kp => kp._id !== id));
            } catch (error) {
                console.error('删除失败', error);
            }
        }
    };

    if (loading) return <div style={{ padding: '20px', textAlign: 'center' }}><p>加载中...</p></div>;
    if (error) return <div style={{ padding: '20px', textAlign: 'center', color: 'red' }}><p>{error}</p></div>;

    return (
        <div style={{ padding: '20px', maxWidth: '1200px', margin: '0 auto' }}>
            <div style={{ 
                display: 'flex', 
                justifyContent: 'space-between', 
                alignItems: 'center', 
                marginBottom: '2rem',
                flexWrap: 'wrap'
            }}>
                <h1 style={{ margin: 0, color: '#333' }}>我的知识点</h1>
                <Link to="/kp/new">
                    <button style={{ 
                        padding: '10px 20px', 
                        backgroundColor: '#4CAF50', 
                        color: 'white', 
                        border: 'none', 
                        borderRadius: '4px', 
                        cursor: 'pointer',
                        fontSize: '16px',
                        fontWeight: 'bold'
                    }}>
                        + 新建知识点
                    </button>
                </Link>
            </div>
            
            <div style={{ 
                backgroundColor: '#f8f9fa', 
                padding: '20px', 
                borderRadius: '8px', 
                marginBottom: '2rem',
                boxShadow: '0 2px 4px rgba(0,0,0,0.1)'
            }}>
                <h2 style={{ marginTop: 0, color: '#555' }}>学习指南</h2>
                <p>欢迎使用费曼学习法平台！请按照以下步骤进行学习：</p>
                <ol>
                    <li>创建或选择一个知识点</li>
                    <li>使用"费曼练习"功能复述知识点内容</li>
                    <li>通过"开始测评"检验学习效果</li>
                    <li>根据AI反馈改进理解</li>
                </ol>
            </div>
            
            <div style={{ marginTop: '20px' }}>
                {knowledgePoints.length === 0 ? (
                    <div style={{ 
                        textAlign: 'center', 
                        padding: '40px', 
                        backgroundColor: '#fff',
                        borderRadius: '8px',
                        boxShadow: '0 2px 4px rgba(0,0,0,0.1)'
                    }}>
                        <h3 style={{ color: '#666' }}>暂无知识点</h3>
                        <p style={{ color: '#999' }}>你还没有任何知识点，快去创建一个吧！</p>
                        <Link to="/kp/new">
                            <button style={{ 
                                padding: '10px 20px', 
                                backgroundColor: '#2196F3', 
                                color: 'white', 
                                border: 'none', 
                                borderRadius: '4px', 
                                cursor: 'pointer'
                            }}>
                                创建第一个知识点
                            </button>
                        </Link>
                    </div>
                ) : (
                    <div style={{ 
                        display: 'grid', 
                        gridTemplateColumns: 'repeat(auto-fill, minmax(350px, 1fr))', 
                        gap: '20px' 
                    }}>
                        {knowledgePoints.map((kp) => (
                            <div 
                                key={kp._id} 
                                style={{ 
                                    border: '1px solid #ddd', 
                                    borderRadius: '8px', 
                                    padding: '15px',
                                    backgroundColor: '#fff',
                                    boxShadow: '0 2px 4px rgba(0,0,0,0.1)',
                                    transition: 'transform 0.2s, box-shadow 0.2s'
                                }}
                                onMouseEnter={(e) => {
                                    e.currentTarget.style.transform = 'translateY(-5px)';
                                    e.currentTarget.style.boxShadow = '0 4px 8px rgba(0,0,0,0.15)';
                                }}
                                onMouseLeave={(e) => {
                                    e.currentTarget.style.transform = 'translateY(0)';
                                    e.currentTarget.style.boxShadow = '0 2px 4px rgba(0,0,0,0.1)';
                                }}
                            >
                                <h2 style={{ 
                                    margin: '0 0 10px 0', 
                                    color: '#333',
                                    fontSize: '1.2rem'
                                }}>
                                    {kp.title}
                                </h2>
                                <div className="markdown-content" style={{ 
                                    background: '#f9f9f9', 
                                    padding: '10px', 
                                    borderRadius: '5px',
                                    maxHeight: '150px',
                                    overflow: 'hidden',
                                    position: 'relative'
                                }}>
                                    <ReactMarkdown 
                                        remarkPlugins={[remarkGfm, remarkMath]}
                                        rehypePlugins={[rehypeKatex]}
                                    >
                                        {kp.content}
                                    </ReactMarkdown>
                                </div>
                                <div style={{ 
                                    display: 'flex', 
                                    justifyContent: 'space-between', 
                                    alignItems: 'center',
                                    marginTop: '15px'
                                }}>
                                    <span style={{ 
                                        padding: '4px 8px', 
                                        backgroundColor: kp.status === 'active' ? '#4CAF50' : '#ff9800',
                                        color: 'white',
                                        borderRadius: '4px',
                                        fontSize: '0.8rem'
                                    }}>
                                        {kp.status === 'active' ? '活跃' : '复习'}
                                    </span>
                                    <div>
                                        <Link to={`/kp/edit/${kp._id}`}>
                                            <button style={{ 
                                                padding: '6px 12px', 
                                                backgroundColor: '#ffc107', 
                                                color: '#333',
                                                border: 'none',
                                                borderRadius: '4px',
                                                cursor: 'pointer',
                                                marginRight: '5px',
                                                fontSize: '0.9rem'
                                            }}>
                                                编辑
                                            </button>
                                        </Link>
                                        <Link to={`/feynman-record/${kp._id}`}>
                                            <button style={{ 
                                                padding: '6px 12px', 
                                                backgroundColor: '#4CAF50', 
                                                color: 'white',
                                                border: 'none',
                                                borderRadius: '4px',
                                                cursor: 'pointer',
                                                marginRight: '5px',
                                                fontSize: '0.9rem'
                                            }}>
                                                费曼练习
                                            </button>
                                        </Link>
                                        <Link to={`/quiz/${kp._id}`}>
                                            <button style={{ 
                                                padding: '6px 12px', 
                                                backgroundColor: '#2196F3', 
                                                color: 'white',
                                                border: 'none',
                                                borderRadius: '4px',
                                                cursor: 'pointer',
                                                marginRight: '5px',
                                                fontSize: '0.9rem'
                                            }}>
                                                测评
                                            </button>
                                        </Link>
                                        <button 
                                            onClick={() => handleDelete(kp._id)} 
                                            style={{ 
                                                padding: '6px 12px', 
                                                backgroundColor: '#f44336', 
                                                color: 'white',
                                                border: 'none',
                                                borderRadius: '4px',
                                                cursor: 'pointer',
                                                fontSize: '0.9rem'
                                            }}
                                        >
                                            删除
                                        </button>
                                    </div>
                                </div>
                            </div>
                        ))}
                    </div>
                )}
            </div>
        </div>
    );
}
export default DashboardPage;